const { copyFileSync } = require("fs");
const {execSQL} = require("../db/mysql") 

const getlist = (author,keyword)=>{
    let sql = `select * from blogs where 1=1 `;
    if(author){
        sql+=`and author = '${author}' `
    }
    if(keyword){
        sql+=`and title like '%${keyword}%' `
    }  
    return execSQL(sql);
}
const getdetail = (id)=>{
    let sql = `select * from blogs where id = '${id}' `;
    return execSQL(sql).then((row)=>{
        console.log('row',row);
        return row[0];
    })
}
const createNewBlog =(blogdata={})=>{
    const {title,content,author} = blogdata;
    const createAt = Date.now();
    const sql = `insert into blogs (title,content,author,createAt) values ('${title}','${content}','${author}','${createAt}')`
    return execSQL(sql).then(insertedResult=>{
        console.log('insertedResult',insertedResult);
        return {
            id:insertedResult.insertId
        }
    })
    
}
const updateBlogData=(id,blogdata)=>{
    const {title,content} = blogdata;
    const sql = `update blogs set title='${title}',content='${content}' where id = '${id}'`
    return execSQL(sql).then(updatedResult=>{
        console.log('updataResult',updatedResult);
        if(updatedResult.affectedRows > 0){
            return true;
        }
        return false;
    })
}
const deleteBlogData=(id,author)=>{
    const sql = `delete from blogs where id = '${id}' and author = '${author}'`
    return execSQL(sql).then(deletedResult=>{
        console.log('deletedResult',deletedResult);
        if(deletedResult.affectedRows > 0){
            return true;
        }
        return false;
    })
}
module.exports = {
    getlist,
    getdetail,
    createNewBlog,
    updateBlogData,
    deleteBlogData
}